﻿using PeaceBlogData;
using PeaceBlogData.Tables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PeaceBlog
{
    public class SiteHelpers
    {

        private static IEnumerable<Settings> _SiteSettings;
        public static IEnumerable<Settings> SiteSettings
        {
            get
            {
                if (HttpContext.Current.Cache["Settings"] != null)
                    _SiteSettings = HttpContext.Current.Cache["Settings"] as IEnumerable<Settings>;
                else
                {
                    using (PeaceBlogEntity context = new PeaceBlogEntity())
                    {
                        _SiteSettings = context.GetAllSettingsWithoutAsync();
                    }
                    HttpContext.Current.Cache["Settings"] = _SiteSettings;
                }
                return _SiteSettings;
            }
            set
            {
                _SiteSettings = value;
                HttpContext.Current.Cache["Settings"] = _SiteSettings;
            }
        }

        public static string GetSetting(string key)
        {
            var vle = (from vl in SiteSettings
                       where vl.Key == key
                       select vl).FirstOrDefault();
            return (vle != null) ? vle.Value : "";
        }

        #region Cookie

        public static void WriteCookie(string key, string value, bool rememberForAday)
        {
            var cookie = HttpContext.Current.Request.Cookies[key];
            if (cookie == null || string.IsNullOrEmpty(cookie.Value))
            {
                cookie = new HttpCookie(key, value);
            }
            cookie.Expires = DateTime.Now.AddDays(1);
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        public static string GetCookieValue(string key)
        {
            var cookie = HttpContext.Current.Request.Cookies[key];
            if (cookie != null)
            {
                return cookie.Value;
            }
            return null;
        }

        public static void RemoveCookie(string key)
        {
            if (HttpContext.Current.Request.Cookies[key] != null)
            {
                var c = new HttpCookie(key);
                c.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(c);
            }
        }

        #endregion

    }
}